package com.spotimage.wsn.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class MiniHTTPServer
{
	
	public MiniHTTPServer(final HashMap<String, String> receivedMsgs)
	{
		try
		{
			final ServerSocket socket = new ServerSocket(80, 10, InetAddress.getByName("127.0.0.1"));
			System.out.println("Listening on: " + socket.getInetAddress() + " port " + socket.getLocalPort());
			
			// setup request handler
			ExecutorService	pool = Executors.newSingleThreadExecutor();
			Runnable handler = new Runnable() {
				public void run()
				{
					try
					{
						while (true)
						{
							Socket s = socket.accept();
							//System.out.println("\nReceived Notification");
							BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
							String line = null;
							String path = null;
							boolean readBody = false;
							StringBuffer buffer = new StringBuffer();
														
							while ((line = reader.readLine()) != null)
							{
								//System.out.println(line);
								if (readBody)
								{
									buffer.append(line + "\n");
									if (line.equals("</soap:Envelope>"))
										break;
								}
								else if (line.startsWith("POST"))
									path = line.substring(line.indexOf(" ")+1, line.indexOf("HTTP")).trim();
								else if (line.length() == 0)
									readBody = true;
							}
							
							//System.out.println("at " + path + "\n" + buffer.toString());
							receivedMsgs.put(path, buffer.toString());
							
							Writer writer = new OutputStreamWriter(s.getOutputStream());
							writer.write("HTTP/1.1 200 OK\13\10");
							writer.write("Content-Length: 0\13\10\13\10");
							writer.flush();
							
							writer.close();
							reader.close();
							s.close();
						}
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
				}
			};
			pool.execute(handler);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
